package org.elec.mac.wxpay;


import com.github.wxpay.sdk.WXPayConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

@Slf4j
public class WXPayConfigImpl implements WXPayConfig {

    private String appid;

    private String mchid;

    private String key;

    private String certpath;

    private byte[] certData;
    private static WXPayConfigImpl INSTANCE;

    private WXPayConfigImpl() throws Exception {
        File file = new File(certpath);
        InputStream certStream = new FileInputStream(file);
        this.certData = new byte[(int) file.length()];
        certStream.read(this.certData);
        certStream.close();
    }

    private WXPayConfigImpl(String appid, String mchid, String key, String certpath) throws Exception {
        this.appid = appid;
        this.mchid = mchid;
        this.key = key;
        this.certpath = certpath;
        File file = new File(certpath);
        InputStream certStream = new FileInputStream(file);
        this.certData = new byte[(int) file.length()];
        certStream.read(this.certData);
        certStream.close();
    }

    public static WXPayConfigImpl getInstance(String appid, String mchid, String key, String certpath) throws Exception {
        if(INSTANCE == null) {
            synchronized(WXPayConfigImpl.class) {
                if(INSTANCE == null) {
                    INSTANCE = new WXPayConfigImpl(appid, mchid, key, certpath);
                }
            }
        }
        return INSTANCE;
    }

    public String getAppID() {
        return appid;
    }

    public String getMchID() {
        return mchid;
    }

    public String getKey() {
        return key;
    }

    public InputStream getCertStream() {
        ByteArrayInputStream certBis;
        certBis = new ByteArrayInputStream(this.certData);
        return certBis;
    }

    public int getHttpConnectTimeoutMs() {
        return 2000;
    }

    public int getHttpReadTimeoutMs() {
        return 10000;
    }

}
